package com.igorkundovic.guitarstab.pages;

import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.CleanupRender;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.igorkundovic.guitarstab.Tab;
import com.igorkundovic.guitarstab.User;
import com.igorkundovic.guitarstab.beans.TabBean;
import com.igorkundovic.guitarstab.service.TabService;

public class UsersTabs {

	
	@ApplicationState
	@Property
	private User user;
	private boolean userExists;
	@Inject
	private TabService tabservice;	
	@Property
	private List<Tab> tabs=new LinkedList<Tab>();
	@Property 
	private TabBean tabbean;
	@Property
	@Persist
	private String message2;

	
	
	public Object onActivate(){
		if(userExists){
			return null;
		}
		return Welcome.class;
	}
	
	@SetupRender
	void setUp(){
		tabs=tabservice.retrieveMine(user);
        String messsage3=null;
		
		if(tabs.isEmpty())
			messsage3="You haven't posted any tab! If you want to post some, click on link Upload tabs...";
		
		message2=messsage3;
	}
	
	@OnEvent(component="deletetab")
	public Object delete(Long id){
		tabs=tabservice.retrieveMine(user);
		for (int i = 0; i < tabs.size(); i++) {
			if(tabs.get(i).getId().equals(id)){
				File file=new File("src\\main\\webapp\\tabs\\" + tabs.get(i).getName());
				file.delete();
				tabs.get(i).setUser(null);
				if(tabservice.delete(tabs.get(i)))
					return this;
			}	
		}	
		
			return Index.class;
		
	}
	
	@CleanupRender
	public void cleanUp(){
		message2=null;
		}
}
